<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      canvas {
        display: block;
        margin: 1em auto;
        border: 2px solid #000;
      }
    </style>
  </head>
  <body>
    <canvas></canvas>
    <script>
      const cvs = document.querySelector("canvas");
      const ctx = cvs.getContext("2d");
      // 把图片绘制到canvas上
      function init() {
        const img = new Image();
        img.onload = () => {
          cvs.width = img.width;
          cvs.height = img.height;
          ctx.drawImage(img, 0, 0);
        };
        img.src = "../img/red-hat.jpg";
        // img.setAttribute("crossOrigin", "anonymous"); // 这允许图片进行跨域访问
      }
      init();
      /*
        - 把鼠标点击位置周围的相近颜色改色
         1. 获取点击坐标 
         2. 获取点击位置的颜色 
    */
      cvs.addEventListener("click", (e) => {
        // 获取点击坐标
        const x = e.offsetX,
          y = e.offsetY;
        console.log(x, y);
        // 获取这张图片上的所有像素点的颜色
        // ctx.drawImage(this, 0, 0);
        const imgData = ctx.getImageData(0, 0, cvs.width, cvs.height);
        console.log(imgData);
      });
    </script>
  </body>
</html>
